package interfaces;

import java.awt.MenuItem;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import cliente.Cliente;
import utils.Utilities;
import dados.Accao;
import dados.Stock;
import eventos.TableAccaoEvent;
import eventos.TableStockEvent;
import gestores.GestorInterfaces;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;

public class EcranInicial extends VBox {

	@FXML
	private Label saldo;
	@FXML
	private TableView<Stock> tableStocks;
	@FXML
	private TableView<Accao> tableAccoes;
	@FXML
	private TextArea agenteTextArea;
	@FXML
	protected Label welcomeUser;
	@FXML
	private TextField searchAll;
	@FXML
	private TextField searchOwn;
	@FXML
	protected Label labelAjudaPrincipal;
	@FXML
	protected Label labelAjudaJogador;
	@FXML
	private Menu config;
	@FXML
	private MenuItem menuItem;
	private URI url;
	private URI ajuda;
	@FXML
	private Hyperlink link;

	private Stage stage;
	private Cliente cliente;
	private GestorInterfaces interfaces;

	public EcranInicial(Stage stage, Cliente cliente, GestorInterfaces interfaces, TextArea agenteTextArea) {
		this.stage = stage;
		this.cliente = cliente;
		this.interfaces = interfaces;
		this.agenteTextArea = agenteTextArea;
		criarJanelaInicial();
	}

	public void criarJanelaInicial() {
		FXMLLoader inicial = new FXMLLoader(getClass().getResource("EcranInicial.fxml"));
		inicial.setRoot(this);
		inicial.setController(this);

		try {
			inicial.load();
		} catch (IOException exception) {
			throw new RuntimeException(exception);
		}
		System.out.println("JANELA INICIAL");
		System.out.println("Pontos: " + cliente.getJogador().getPontos());
		saldo.setText(Utilities.roundTo2DecimalsString(cliente.getJogador().getSaldo()) + "$");
		System.out.println("Saldo: " + cliente.getJogador().getSaldo());
		welcomeUser.setText(cliente.getJogador().getNome());
		adicionarItemMenu();
		agenteTextArea.setText("Liga��o entre c�digo e interface conclu�da");
		
		try {
			url = new URI("http://" + link.getText());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		
		try {
			ajuda = new URI("http://46.137.99.16/myStock/Ajuda.jsp");
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		
		stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
		    @Override
		    public void handle(WindowEvent event) {
		    	System.exit(0);
		    }
		});
	}

	@FXML
	 public void irParaSite(ActionEvent e) {
		 try {
			java.awt.Desktop.getDesktop().browse(url);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
   }
	
	@FXML
	public void perfilJogadorUserLabel(MouseEvent event) {
		stage.close();
		interfaces.ecranJogador(new Stage());
	}

	@FXML
	public void ecranInicialHomeImage(MouseEvent event) {
		stage.close();
		interfaces.ecranInicial(new Stage());
	}

	@FXML
	public void ExitOption(ActionEvent event) {
		interfaces.ecranSair(new Stage());
	}

	@FXML
	public void opcaoAjuda(ActionEvent event) {
		 try {
			java.awt.Desktop.getDesktop().browse(ajuda);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@FXML
	public void logOut(MouseEvent event) {
		interfaces.ecranLogout(new Stage());
	}

	@FXML
	public void mostrarLabelAjudaPrincipal(MouseEvent evente) {
		labelAjudaPrincipal.setOpacity(1);
	}

	@FXML
	public void mostrarLabelAjudaJogador(MouseEvent evente) {
		labelAjudaJogador.setOpacity(1);
	}

	@FXML
	public void esconderLabelAjudaPrincipal(MouseEvent evente) {
		labelAjudaPrincipal.setOpacity(0);
	}

	@FXML
	public void esconderLabelAjudaJogador(MouseEvent evente) {
		labelAjudaJogador.setOpacity(0);
	}

	@FXML
	public void search() {
//		System.out.println("TODAS AS STOCKS: " + cliente.getStocks());
		if(searchAll.getText().trim().equals("")){
			ObservableList<Stock> dataList = FXCollections.observableArrayList(cliente.getStocks());
			tableStocks.setItems(dataList);
		} else {
			ArrayList<Stock> listaSearched = new ArrayList<Stock>();
			for (Stock stockPointer : cliente.getStocks()) {
				if (stockPointer.getNome().toLowerCase().contains(searchAll.getText().toLowerCase())) {
					listaSearched.add(stockPointer);
				}
			}
			ObservableList<Stock> dataList = FXCollections.observableArrayList(listaSearched);
			tableStocks.setItems(dataList);
		}
	}

	@FXML
	public void searchEnter(KeyEvent e) {
		KeyCode key = e.getCode();
		if (key == KeyCode.ENTER){
			search();
		}
	}
	
	@FXML
	public void searchOwn() {
		if(searchOwn.getText().trim().equals("")){
			ObservableList<Accao> dataList = FXCollections.observableArrayList(cliente.getJogador().getAccoes());
			tableAccoes.setItems(dataList);
		} else {
			ArrayList<Accao> listaSearched = new ArrayList<Accao>();
			for (Accao accaoPointer : cliente.getJogador().getAccoes()) {
				if (accaoPointer.getNome().toLowerCase().contains(searchOwn.getText().toLowerCase())) {
					listaSearched.add(accaoPointer);
				}
			}
			ObservableList<Accao> dataList = FXCollections.observableArrayList(listaSearched);
			tableAccoes.setItems(dataList);
		}
	}

	@FXML
	public void searchEnterOwn(KeyEvent e) {
		KeyCode key = e.getCode();
		if (key == KeyCode.ENTER){
			searchOwn();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void tableAllStocks(ObservableList<Stock> listAllStocks) {
		TableColumn<Stock, String> columnNome = new TableColumn<Stock, String>("Nome");
		columnNome.setCellValueFactory(new PropertyValueFactory<Stock, String>("nome"));		
		columnNome.setMinWidth(149);
		columnNome.setPrefWidth(149);

		TableColumn<Stock, String> columnSigla = new TableColumn<Stock, String>("Sigla");
		columnSigla.setCellValueFactory(new PropertyValueFactory<Stock, String>("sigla"));
		columnSigla.setMinWidth(110);
		columnSigla.setPrefWidth(110);

		TableColumn<Stock, Double> columnValue = new TableColumn<Stock, Double>("Valor");
		columnValue.setCellValueFactory(new PropertyValueFactory<Stock, Double>("cotacao"));
		columnValue.setCellFactory(new Callback<TableColumn<Stock,Double>, TableCell<Stock,Double>>() {

			@Override
			public TableCell<Stock, Double> call(TableColumn<Stock, Double> param) {
				return new TableCell<Stock, Double>() {
					@Override
					public void updateItem(Double item, boolean empty) {
						super.updateItem(item, empty);
						if (!isEmpty()) {
							this.setText(Utilities.roundTo2DecimalsString(item));
						}
					}
				};
			}
		});
		columnValue.setMinWidth(110);
		columnValue.setPrefWidth(110);

		TableColumn<Stock, Double> columnVariation = new TableColumn<Stock, Double>("Variacao");
		columnVariation.setCellValueFactory(new PropertyValueFactory<Stock, Double>("variacao"));

		columnVariation.setCellFactory(new Callback<TableColumn<Stock, Double>, TableCell<Stock, Double>>() {

					@Override
					public TableCell<Stock, Double> call(TableColumn<Stock, Double> param) {
						return new TableCell<Stock, Double>() {
							@Override
							public void updateItem(Double item, boolean empty) {
								super.updateItem(item, empty);
								if (!isEmpty()) {
									this.setTextFill(Color.GREEN);
									if (item < 0)
										this.setTextFill(Color.RED);
									setText(Utilities.roundTo2DecimalsString(item) + "%");
								}
							}
						};
					}
				});

		columnVariation.setMinWidth(108);
		columnVariation.setPrefWidth(108);

		tableStocks.setItems(listAllStocks);
		tableStocks.getColumns().addAll(columnNome, columnSigla, columnValue, columnVariation);
		// para nao poder mexer nas colunas
		tableStocks.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		tableStocks.addEventFilter(MouseEvent.MOUSE_CLICKED, new TableStockEvent(tableStocks, stage, interfaces));
	}

	@SuppressWarnings("unchecked")
	public void tableUserStocks(Stage stage, ObservableList<Accao> listUserStocks) {
		TableColumn<Accao, String> columnNome = new TableColumn<Accao, String>("Nome");
		columnNome.setCellValueFactory(new PropertyValueFactory<Accao, String>("nome"));
		columnNome.setMinWidth(130);
		columnNome.setPrefWidth(130);

		TableColumn<Accao, String> columnSigla = new TableColumn<Accao, String>("Sigla");
		columnSigla.setCellValueFactory(new PropertyValueFactory<Accao, String>("sigla"));
		columnSigla.setMinWidth(70);
		columnSigla.setPrefWidth(70);

		TableColumn<Accao, Double> columnValue = new TableColumn<Accao, Double>("Valor");
		columnValue.setCellValueFactory(new PropertyValueFactory<Accao, Double>("valorAquisicao"));
		columnValue.setCellFactory(new Callback<TableColumn<Accao,Double>, TableCell<Accao,Double>>() {

					@Override
					public TableCell<Accao, Double> call(TableColumn<Accao, Double> param) {
						return new TableCell<Accao, Double>() {
							@Override
							public void updateItem(Double item, boolean empty) {
								super.updateItem(item, empty);
								if (!isEmpty()) {
									this.setText(Utilities.roundTo2DecimalsString(item));
								}
							}
						};
					}
				});
		columnValue.setMinWidth(90);
		columnValue.setPrefWidth(90);

		TableColumn<Accao, String> columnVariation = new TableColumn<Accao, String>("Quantidade");
		columnVariation.setCellValueFactory(new PropertyValueFactory<Accao, String>("quantidade"));

		columnVariation.setMinWidth(75);
		columnVariation.setPrefWidth(75);
		
		TableColumn<Accao, Double> columnTotalValue = new TableColumn<Accao, Double>("Total");
		columnTotalValue.setCellValueFactory(new PropertyValueFactory<Accao, Double>("valorTotal"));
		columnTotalValue.setCellFactory(new Callback<TableColumn<Accao,Double>, TableCell<Accao,Double>>() {

					@Override
					public TableCell<Accao, Double> call(TableColumn<Accao, Double> param) {
						return new TableCell<Accao, Double>() {
							@Override
							public void updateItem(Double item, boolean empty) {
								super.updateItem(item, empty);
								if (!isEmpty()) {
									this.setText(Utilities.roundTo2DecimalsString(item));
								}
							}
						};
					}
				});
		columnTotalValue.setMinWidth(80);
		columnTotalValue.setPrefWidth(80);

		tableAccoes.setItems(listUserStocks);
		tableAccoes.getColumns().addAll(columnNome, columnSigla, columnValue, columnVariation, columnTotalValue);
		// para nao poder mexer nas colunas
		tableAccoes.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		tableAccoes.addEventFilter(MouseEvent.MOUSE_CLICKED, new TableAccaoEvent(tableAccoes, interfaces, stage));
	}

	public void adicionarItemMenu() {
		javafx.scene.control.MenuItem newItem = new javafx.scene.control.MenuItem("Adicionar Empresa");
		if (cliente.getJogador().isSuperUser()) {
			config.getItems().add(newItem);
			newItem.setOnAction(new EventHandler<ActionEvent>() {

				@Override
				public void handle(ActionEvent event) {
					interfaces.ecranAddCompanies(new Stage());
					
				}
			});
		}
	}
	
	
	public TableView<Stock> getTableStocks(){
		return tableStocks;
	}

	public TextArea getAgenteTextArea() {
		return agenteTextArea;
	}

	public void setAgenteTextArea(TextArea agenteTextArea) {
		this.agenteTextArea = agenteTextArea;
	}
}